<template>
  <div class="todo-container">
    <div class="todo-wrap">
      <!-- 给Heardr传递添加函数 -->
      <Header :addTodo="addTodo"/>
      <!-- 给list传递数据, 改变单个、删除单个函数  -->
      <List :todoList="todoList" :asignChange="asignChange" :asignDelete="asignDelete"/>
      <!-- 给Footer传递数据, 全选函数 清除已完成函数-->
      <Footer :todoList="todoList" :allCheckedHandle="allCheckedHandle" :deleteSuccessHandle="deleteSuccessHandle"/>
    </div>
  </div>
</template>

<script>
import Header from "./components/Header";
import List from "./components/List";
import Footer from "./components/Footer";
export default {
  name: "App",
  data(){
    return{
      todoList:[]
    }
  },

  methods:{
    //1.添加数据
    addTodo(newTodo){
      //使用变更方法添加数据到数组
      this.todoList.push(newTodo)
    },

    //2.单个选中不选中
    asignChange(id){
      //map改变点击的这条数据的done为取反
      this.todoList = this.todoList.map((item) => {
        return (
          item.id === id ? {...item , done: !item.done} : item
        )
      })
    },

    //3.单个删除
    asignDelete(id){
      //删除提示
      const isDelete = confirm("确定要删除吗")
      if(!isDelete) return

      //过滤掉点击删除地这一个
      this.todoList = this.todoList.filter((item) => {
        return item.id !== id
      })
    },

    //4.点击全选
    allCheckedHandle(value){
      //直接把所有的done设置为true或者false
      this.todoList = this.todoList.map((item) => {
        return {...item , done: value}
      })
    },

    //5.清除已完成
    deleteSuccessHandle(){
      //过滤掉done为true的
      this.todoList = this.todoList.filter((item) => !item.done )
    }

  },
  //数据持久化
  mounted(){
    this.todoList = JSON.parse(localStorage.getItem("todoList") || "[]")
  },

  //监听数据改变把数据设置到本地存储中
  watch:{
    todoList:{
      deep: true,
      handler(){
        localStorage.setItem("todoList" , JSON.stringify(this.todoList))
      }
    }
  },

  components: {
    Header,
    List,
    Footer,
  },
};
</script>

<style>
/*base*/
body {
  background: #fff;
}

.btn {
  display: inline-block;
  padding: 4px 12px;
  margin-bottom: 0;
  font-size: 14px;
  line-height: 20px;
  text-align: center;
  vertical-align: middle;
  cursor: pointer;
  box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2),
    0 1px 2px rgba(0, 0, 0, 0.05);
  border-radius: 4px;
}

.btn-danger {
  color: #fff;
  background-color: #da4f49;
  border: 1px solid #bd362f;
}

.btn-danger:hover {
  color: #fff;
  background-color: #bd362f;
}

.btn:focus {
  outline: none;
}

.todo-container {
  width: 600px;
  margin: 0 auto;
}
.todo-container .todo-wrap {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}
</style>